package com.yifushidai.api;

import com.yifushidai.utils.ApiBaseAction;
import com.yifushidai.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Api(tags = "上传文件")
@RequestMapping("/api/upload_file")
public class ApiUploadFileController extends ApiBaseAction {

    @Value("${server.root}")
    private String server_root;

    @ApiOperation(value = "上传活动图片文件")
    @PostMapping("/save")
    public R save(@ApiParam(value = "文件流", required = true) @RequestBody MultipartFile upLoadFile) throws IOException {
        return R.ok().put(uploadImg(upLoadFile));
    }

    private String uploadImg(MultipartFile file) throws IOException {
        if (file == null) {
            return null;
        }
//        if (!FileUtil.isImage(file.getInputStream())) {
//            return null;
//        }

//        String imgDirectory = request.getSession().getServletContext().getRealPath("/fileStore/imgDirectory/");//物理路径
        String imgDirectory = server_root + "/fileStore/imgDirectory/";
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();//获取的服务器地址

        String uploadFilename = file.getOriginalFilename();
        int index = uploadFilename.lastIndexOf(".");
        if (index < 0) {
            return null;
        }
//        String filename = uploadFilename.substring(0, index) + "_" + UUIDUtils.creatUUID() + uploadFilename.substring(index);
        String filename = uploadFilename;
        file.transferTo(new File(imgDirectory, filename));

        return basePath + "/fileStore/imgDirectory/" + filename;
    }
}